package com.quality.mybatis.utils;

import com.quality.mybatis.pojo.Project;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

import java.util.Date;
import java.util.List;

public class getInfoUtil2 {

    private getInfoUtil2() {
    }

    public static List<Project> getInfo(List<Project> projects, String url, String bearerToken){

        try {

            CloseableHttpClient httpClient = HttpClients.createDefault();

            // 然后把编码结果加到请求头里面去
            HttpPost request = new HttpPost(url);
            request.setHeader("Authorization", "Bearer " + bearerToken);
            request.setHeader("Content-Type", "application/json");

            // 设置请求体内容
            String jsonPayload = "{\"page\":1,\"rows\":65535}";
            StringEntity entity = new StringEntity(jsonPayload);
            request.setEntity(entity);

            HttpResponse response = httpClient.execute(request);

            // 检查响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                String responseBody = EntityUtils.toString(response.getEntity());
                // 使用 Jackson 解析 JSON
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(responseBody);
                // 获取指定键的值
                JsonNode valueNode = rootNode.path("rows");
                if(valueNode != null){
                    int index = 0;
                    for (JsonNode jsonNode : valueNode) {
                        String productName = jsonNode.path("productName").asText();
                        String projectId = jsonNode.path("productId").asText();
                        projects.get(index).setProjectName(productName);
                        projects.get(index).setProjectId(projectId);
                        projects.get(index).setCreateTime(new Date());
                        index++;
                    }
                    return projects;
                }
            } else {
                System.out.println("HTTP 请求失败：" + statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
